package com.xingkeduo.dao.database.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.xingkeduo.util.pojo.base.BaseEnum;

public class IntEnumValueHandler<E extends Enum<E> & BaseEnum> extends BaseTypeHandler<E> {
	private Class<E> type;

	public IntEnumValueHandler(Class<E> type) {
		if (type == null) {
			throw new IllegalArgumentException("Type argument cannot be null");
		}
		this.type = type;
	}

	@Override
	public E getNullableResult(ResultSet arg0, String arg1) throws SQLException {
		return convert(arg0.getInt(arg1));
	}

	@Override
	public E getNullableResult(ResultSet arg0, int arg1) throws SQLException {
		return convert(arg0.getInt(arg1));
	}

	@Override
	public E getNullableResult(CallableStatement arg0, int arg1) throws SQLException {
		return convert(arg0.getInt(arg1));
	}

	@Override
	public void setNonNullParameter(PreparedStatement arg0, int arg1, E arg2, JdbcType arg3)
			throws SQLException {
		System.out.println("11111111111111=============="+arg2.getValue());
		arg0.setInt(arg1, arg2.getValue());
	}

	private E convert(int value) {
		System.out.println("2222222222222222=============="+type.getName());
		E[] objs = (E[]) type.getEnumConstants();
		for (E em : objs) {
			if (em.getValue() == value) {
				return em;
			}
		}
		return null;
	}
}
